/**
 * Date:2021年3月30日 上午11:41:55
 * Copyright (c) 2021, www.bwbroad.com All Rights Reserved
 */

package com.app.common.core;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mysql.cj.MysqlConnection;
import com.mysql.cj.jdbc.ConnectionImpl;
import com.mysql.cj.jdbc.interceptors.ConnectionLifecycleInterceptor;
import com.mysql.cj.log.Log;

/**
 * Description: MySQL生命周期拦截器 <br/>
 * Date:2021年3月30日 上午11:41:55 <br/>
 * 
 * @author xuejianxin
 */
public class MySqlConnectionLifecycleInterceptor implements ConnectionLifecycleInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(MySqlConnectionLifecycleInterceptor.class);

	private ConnectionImpl conn;

	@Override
	public ConnectionLifecycleInterceptor init(MysqlConnection conn, Properties props, Log log) {
		// logger.info("ConnectionLifecycleInterceptor init,conn id={},props={} ",
		// conn.getId(), props);
		logger.info("conn id={}  init", conn.getId());
		this.conn = (ConnectionImpl) conn;
		return this;
	}

	@Override
	public void destroy() {
		logger.info("conn id={} destroy", conn.getId());
		this.conn = null;
	}

	@Override
	public void close() throws SQLException {
		logger.info("conn id={} close", conn.getId());
	}

	@Override
	public boolean commit() throws SQLException {
		logger.info("conn id={} commit", conn.getId());
		return true;
	}

	@Override
	public boolean rollback() throws SQLException {
		logger.info("conn id={} rollback true", conn.getId());
		return true;
	}

	@Override
	public boolean rollback(Savepoint s) throws SQLException {
		logger.info("conn id={} rollback", conn.getId());
		return true;
	}

	@Override
	public boolean setAutoCommit(boolean flag) throws SQLException {
		// logger.info("conn id={} setAutoCommit={}", conn.getId(), flag);
		if (!flag) {
			try (Statement stmt = conn.createStatement();
					ResultSet rs = stmt.executeQuery("select @@server_id , @@hostname ")) {
				boolean readOnly = this.conn.isReadOnly();
				if (rs.next()) {
					logger.info("conn id={} setAutoCommit=false serverid={},hostname={},readOnly={}", conn.getId(),
							rs.getString(1), rs.getString(2), readOnly);
				}
			} catch (SQLException e) {
				logger.error("transactionBegun", e);
			}
		}
		return true;
	}

	@Override
	public boolean setDatabase(String db) throws SQLException {
		// logger.info("conn id={} setDatabase={}", conn.getId(), db);
		return true;
	}

	// 好像没用不知道在什么时候触发
	@Override
	public boolean transactionBegun() {
		logger.info("conn id={} transactionBegun", conn.getId());

		return true;
	}

	// 好像没用不知道在什么时候触发
	@Override
	public boolean transactionCompleted() {
		logger.info("conn id={} transactionCompleted", conn.getId());
		return true;
	}

}
